package vn.bus.bk;

import java.util.ArrayList;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

import vn.bus.bk.object.BusHolder;
import vn.bus.bk.object.BusInfo;
import vn.bus.bk.object.BusTwoRouteInfo;
import vn.bus.bk.other.AnimationEditText;
import vn.bus.bk.other.Convert;
import vn.bus.bk.adapter.ListBusAdapter;
import vn.bus.bk.adapter.ListTwoPlaceAdapter;
import vn.bus.bk.adapter.SQLiteAdapter;
import vn.bus.bk.dialog.DialogMessage;import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;

public class SearchByTwoPlace extends SherlockFragmentActivity implements OnClickListener {

    private Button search;
    private AutoCompleteTextView firstPlace, lastPlace;
    private ArrayAdapter<String> adapter;
    private ListView myList;
    private SQLiteAdapter mySQLAdapter;
    private ListBusAdapter myBusAdapter;
    private ListTwoPlaceAdapter myTwoPlaceAdapter;
    private Cursor mCursor;
    private String first, last;
    private int iNumber, iGoBus, iBackBus, iName, iTimeStartBus, iTimeEndBus,
	    iFrequency, iValue, iOrdinateGo, iOrdinateBack;
    private String[] columns ;
    private ArrayList<BusHolder> listForFirst, listForLast;
    private ArrayList<BusTwoRouteInfo> listForTwoPlace;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.searchbytwoplace);
	setTitle(getString(R.string.menu_item_3));	
	getSupportActionBar().setDisplayHomeAsUpEnabled(true);
	getSupportActionBar().setHomeButtonEnabled(true);
	getWindow().setSoftInputMode(
		WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	columns = getResources().getStringArray(R.array.arrayColumn);
	createAdapter();
	init();
    }

    private void init() {
	// TODO Auto-generated method stub
	search = (Button) findViewById(R.id.btSearchTwoPlace);
	firstPlace = (AutoCompleteTextView) findViewById(R.id.autoTextFirstPlace);
	lastPlace = (AutoCompleteTextView) findViewById(R.id.autoTextLastPlace);
	myList = (ListView) findViewById(R.id.listTwoPlace);
	firstPlace.setAdapter(adapter);
	lastPlace.setAdapter(adapter);
	search.setOnClickListener(this);
    }

    private void createAdapter() {
	
	String[] array ;
	if(SQLiteAdapter.getNameCity(this) == 1){
	    array = getResources().getStringArray(R.array.arrayPlaceHN);
	}else{
	    array = getResources().getStringArray(R.array.arrayPlaceHCM);
	}
	
	adapter = new ArrayAdapter<String>(this,
		android.R.layout.simple_dropdown_item_1line, array);
    }

    public void onClick(View arg0) {
	// TODO Auto-generated method stub
	// first = firstPlace.getText().toString();
	// last = lastPlace.getText().toString();

	first = firstPlace.getEditableText().toString();
	last = lastPlace.getEditableText().toString();

	first = standardizeInput(first);
	last = standardizeInput(last);
	Log.i("FIRST", first);
	Log.i("LAST", last);
	first = first.trim();
	last = last.trim();
	Log.i("TAG", "Clicked");
	if (first == null | last == null | first.length() == 0
		| last.length() == 0) {
//	    DialogMessage dialogMessage = new DialogMessage(
//		    SearchByTwoPlace.this, getString(R.string.not_enough_data_input));
//	    dialogMessage.show(false);
	    
	    showAnimationAlarm();
	} else {
	    loadDataFromDatabase();

	    FindOneAsynTask taskFindOne = new FindOneAsynTask(
		    SearchByTwoPlace.this);
	    taskFindOne.execute("Find One");
	}
    }
    
    private void showAnimationAlarm(){
	AnimationEditText.shakeAnimation(this, firstPlace);
	AnimationEditText.shakeAnimation(this, lastPlace);
    }
    private boolean findOneRoute() {
	ArrayList<BusInfo> myListBus = new ArrayList<BusInfo>();

	try {
	    mCursor.moveToFirst();

	    do {
		String go = standardizeRoute(mCursor.getString(iGoBus));
		String back = standardizeRoute(mCursor.getString(iBackBus));
		if (check(first, go) && check(last, go)) {
		    if (go.indexOf(first) < go.indexOf(last)) {
			myListBus.add(new BusInfo(mCursor.getInt(iNumber),
				mCursor.getString(iName), mCursor
					.getString(iGoBus), mCursor
					.getString(iBackBus), mCursor
					.getString(iTimeStartBus), mCursor
					.getString(iTimeEndBus), mCursor
					.getString(iFrequency), mCursor
					.getString(iValue), mCursor
					.getString(iOrdinateGo), mCursor
					.getString(iOrdinateBack)));
		    }
		}
		if (check(first, back) && check(last, back)) {
		    if (back.indexOf(first) < back.indexOf(last)) {
			myListBus.add(new BusInfo(mCursor.getInt(iNumber),
				mCursor.getString(iName), mCursor
					.getString(iGoBus), mCursor
					.getString(iBackBus), mCursor
					.getString(iTimeStartBus), mCursor
					.getString(iTimeEndBus), mCursor
					.getString(iFrequency), mCursor
					.getString(iValue), mCursor
					.getString(iOrdinateGo), mCursor
					.getString(iOrdinateBack)));
		    }
		}
		mCursor.moveToNext();
	    } while (!mCursor.isAfterLast());

	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

	if (myListBus.size() == 0) {
	    return false;
	} else {
	    myBusAdapter = new ListBusAdapter(this, myListBus);
	    mySQLAdapter.close();
	    return true;
	}
    }

    private boolean findTwoRoute() {
	listForFirst = new ArrayList<BusHolder>();
	listForLast = new ArrayList<BusHolder>();
	listForTwoPlace = new ArrayList<BusTwoRouteInfo>();
	createTwoArrayListForTwoPlace();
	return isListTwoPlace();

    }

    private void createTwoArrayListForTwoPlace() {
	// TODO Auto-generated method stub
	try {
	    mCursor.moveToFirst();

	    do {
		String go = standardizeRoute(mCursor.getString(iGoBus));
		String back = standardizeRoute(mCursor.getString(iBackBus));
		int numberOfRouteFirst = -2;
		boolean isGoFirst = check(first, go);
		boolean isBackFirst = check(first, back);
		if (isGoFirst && isBackFirst) {
		    numberOfRouteFirst = 0;
		} else if (isGoFirst) {
		    numberOfRouteFirst = -1;
		} else if (isBackFirst) {
		    numberOfRouteFirst = 1;
		}
		if (numberOfRouteFirst != -2) {
		    listForFirst.add(new BusHolder(numberOfRouteFirst,
			    new BusInfo(mCursor.getInt(iNumber), mCursor
				    .getString(iName), mCursor
				    .getString(iGoBus), mCursor
				    .getString(iBackBus), mCursor
				    .getString(iTimeStartBus), mCursor
				    .getString(iTimeEndBus), mCursor
				    .getString(iFrequency), mCursor
				    .getString(iValue), mCursor
				    .getString(iOrdinateGo), mCursor
				    .getString(iOrdinateBack))));
		} else {
		    int numberOfRouteLast = -2;
		    boolean isGoLast = check(last, go);
		    boolean isBackLast = check(last, back);
		    if (isGoLast && isBackLast) {
			numberOfRouteLast = 0;
		    } else if (isGoLast) {
			numberOfRouteLast = -1;
		    } else if (isBackLast) {
			numberOfRouteLast = 1;
		    }
		    if (numberOfRouteLast != -2) {
			listForLast.add(new BusHolder(numberOfRouteLast,
				new BusInfo(mCursor.getInt(iNumber), mCursor
					.getString(iName), mCursor
					.getString(iGoBus), mCursor
					.getString(iBackBus), mCursor
					.getString(iTimeStartBus), mCursor
					.getString(iTimeEndBus), mCursor
					.getString(iFrequency), mCursor
					.getString(iValue), mCursor
					.getString(iOrdinateGo), mCursor
					.getString(iOrdinateBack))));
		    }
		}
		mCursor.moveToNext();
	    } while (!mCursor.isAfterLast());

	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	mySQLAdapter.close();

    }

    private boolean isListTwoPlace() {
	for (int i = 0; i < listForFirst.size(); i++) {
	    BusHolder firstBus = listForFirst.get(i);
	    String[] arrayPlace;
	    if (firstBus.getNumberOfRoate() == 0) {
		String routeToFind = firstBus.getBus().getBusGo();
		arrayPlace = routeToFind.split("-");
	    } else {
		String routeToFind = standardizeRoute(firstBus.getRouteToFind());
		int position = routeToFind.indexOf(first);
		String stringArrayGo = firstBus.getRouteToFind().substring(
			position + first.length());
		arrayPlace = stringArrayGo.split("-");
	    }

	    // arrayPlace = firstBus.getRoute().split("-");
	    if (arrayPlace.length == 0)
		continue;
	    for (int j = 0; j < listForLast.size(); j++) {
		ArrayList<String> allPlaceChange = new ArrayList<String>();
		for (int k = 0; k < arrayPlace.length; k++) {
		    String keyPlace = arrayPlace[k];
		    keyPlace = keyPlace.trim();
		    String keyPlaceToFind = keyPlace.toLowerCase();
		    keyPlaceToFind = standardizeRoute(keyPlaceToFind);
		    Log.i("KEY PLACE", keyPlace);
		    Log.i("KEY PLACE TO FIND", keyPlaceToFind);
		    BusHolder lastBus = listForLast.get(j);
		    String routeLastToFind;
		    if (lastBus.getNumberOfRoate() == 0) {
			routeLastToFind = standardizeRoute(lastBus.getBus()
				.getBusGo());
		    } else {
			String route = standardizeRoute(lastBus
				.getRouteToFind());
			Log.i("LENGTH", String.valueOf(route.length()));
			int position = route.indexOf(last);
			Log.i("POSITION", String.valueOf(position));
			routeLastToFind = route.substring(0, position);
		    }
		    // routeLastToFind = lastBus.getRouteToFind();
		    if (check(keyPlaceToFind, routeLastToFind)) {
			allPlaceChange.add(keyPlace);
		    }
		}
		if (allPlaceChange.size() != 0) {
		    listForTwoPlace.add(new BusTwoRouteInfo(listForFirst.get(i)
			    .getBus(), listForLast.get(j).getBus(),
			    allPlaceChange));
		}
	    }

	}
	if (listForTwoPlace.size() != 0) {
	    myTwoPlaceAdapter = new ListTwoPlaceAdapter(this, listForTwoPlace);
	    return true;
	}
	return false;
    }

    private void loadDataFromDatabase() {

	mySQLAdapter = new SQLiteAdapter(this);
	try {
	    mySQLAdapter.close();
	    mySQLAdapter.copyDataBase();
	    mySQLAdapter.openDataBase();

	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    Log.i("DATABASE", "Cannot connect to database");
	}

	try {
	    mCursor = mySQLAdapter.rawAll();
	    initialzeIndex();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    private void initialzeIndex() {
	iNumber = mCursor.getColumnIndex(columns[0]);
	iGoBus = mCursor.getColumnIndex(columns[1]);
	iBackBus = mCursor.getColumnIndex(columns[2]);
	iName = mCursor.getColumnIndex(columns[3]);
	iTimeStartBus = mCursor.getColumnIndex(columns[4]);
	iTimeEndBus = mCursor.getColumnIndex(columns[5]);
	iFrequency = mCursor.getColumnIndex(columns[6]);
	iValue = mCursor.getColumnIndex(columns[7]);
	iOrdinateGo = mCursor.getColumnIndex(columns[8]);
	iOrdinateBack = mCursor.getColumnIndex(columns[9]);
    }

    private String standardizeInput(String input) {
	input = input.toLowerCase();
	input = Convert.convert(input);
	return input;
    }

    private String standardizeRoute(String input) {
	input = input.toLowerCase();
	input = Convert.convertRoute(input);
	return input;
    }

    private boolean check(String input, String output) {
	int n = input.length();
	int m = output.length();
	for (int i = 0; i < m - n + 1; i++) {
	    String s = output.substring(i, i + n);
	    if (s.equals(input))
		return true;
	}
	return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub
	if (item.getItemId() == android.R.id.home) {
	    finish();
	}
	return super.onOptionsItemSelected(item);
    }
    public class FindOneAsynTask extends AsyncTask<String, Integer, String> {

	private Context mContext;
	private boolean isFinded;
	private ProgressDialog dialog;

	public FindOneAsynTask(Context context) {
	    this.mContext = context;
	    Log.i("TAG", "Contructor");
	}

	@Override
	protected void onPreExecute() {
	    // TODO Auto-generated method stub
	    super.onPreExecute();
	    this.dialog = new ProgressDialog(mContext);
	    this.dialog.setMessage("Loading.....");
	    this.dialog.show();

	}

	@Override
	protected String doInBackground(String... arg0) {
	    // TODO Auto-generated method stub
	    isFinded = findOneRoute();
	    return null;
	}

	@Override
	protected void onPostExecute(String result) {
	    // TODO Auto-generated method stub
	    super.onPostExecute(result);
	    if (dialog.isShowing()) {
		dialog.dismiss();
	    }
	    if (isFinded) {
		myList.setAdapter(myBusAdapter);
	    } else {
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(getString(R.string.announce));
		builder.setMessage(getString(R.string.not_find_and_require_find_two_place));
		builder.setPositiveButton("OK",
			new DialogInterface.OnClickListener() {

			    public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				FindTwoTask taskFindTwo = new FindTwoTask(
					SearchByTwoPlace.this);
				taskFindTwo.execute("Find two");

			    }
			});
		builder.setNegativeButton(getString(R.string.cancel),
			new DialogInterface.OnClickListener() {

			    public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				// mySQLAdapter.close();
			    }
			});
		builder.setCancelable(false);
		builder.show();

	    }

	}

    }

    public class FindTwoTask extends AsyncTask<String, Integer, String> {

	private Context mContext;
	private boolean isFinded;
	private ProgressDialog dialog;

	public FindTwoTask(Context context) {
	    this.mContext = context;
	    Log.i("TAG", "Contructor");
	}

	@Override
	protected void onPreExecute() {
	    // TODO Auto-generated method stub
	    super.onPreExecute();
	    this.dialog = new ProgressDialog(mContext);
	    this.dialog.setMessage("Loading.....");
	    this.dialog.show();

	}

	@Override
	protected String doInBackground(String... arg0) {
	    // TODO Auto-generated method stub
	    isFinded = findTwoRoute();
	    return null;
	}

	@Override
	protected void onPostExecute(String result) {
	    // TODO Auto-generated method stub
	    super.onPostExecute(result);
	    if (dialog.isShowing()) {
		dialog.dismiss();
	    }
	    if (isFinded) {
		myList.setAdapter(myTwoPlaceAdapter);
	    } else {
		DialogMessage dialogmessage = new DialogMessage(mContext,
			getString(R.string.not_find_two_place));
		dialogmessage.show(false);
	    }

	}

    }

}


